const axios = require('axios');

(async () => {
  console.log('🧪 验证勋章筛选功能修复');
  
  try {
    // 1. 登录用户
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'admin@campus.com',
      password: 'admin123'
    });
    
    const authToken = loginResponse.data.token;
    const userId = loginResponse.data.user.id;
    console.log(`✅ 用户登录成功: ID=${userId}`);
    
    // 2. 获取三种筛选模式下的勋章
    console.log('\n🏆 获取勋章数据...');
    
    // "全部勋章"
    const allBadgesResponse = await axios.get('http://localhost:3000/api/badges', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    // "我的勋章"
    const ownedBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=owned', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    // "可获得勋章"
    const availableBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=available', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    // 3. 验证数量
    const ownedCount = ownedBadgesResponse.data.badges.length;
    const availableCount = availableBadgesResponse.data.badges.length;
    const totalCount = allBadgesResponse.data.badges.length;
    
    console.log('\n📊 勋章数量统计:');
    console.log(`全部勋章: ${totalCount}个`);
    console.log(`我的勋章: ${ownedCount}个`);
    console.log(`可获得勋章: ${availableCount}个`);
    
    if (ownedCount + availableCount === totalCount) {
      console.log('✅ 数量验证通过: 全部勋章 = 我的勋章 + 可获得勋章');
    } else {
      console.log('❌ 数量验证失败: 全部勋章 ≠ 我的勋章 + 可获得勋章');
      console.log(`   ${ownedCount} + ${availableCount} = ${ownedCount + availableCount}, 但全部勋章为 ${totalCount}`);
    }
    
    // 4. 验证"我的勋章"是否全部为已获得状态
    const ownedVerification = ownedBadgesResponse.data.badges.every(badge => 
      badge.isOwned === true || (badge.status === 'minted' && badge.user_id === userId)
    );
    
    console.log('\n🔍 我的勋章验证:');
    if (ownedVerification) {
      console.log('✅ "我的勋章"全部为已获得状态');
    } else {
      console.log('❌ "我的勋章"中存在未获得的勋章');
      const invalidBadges = ownedBadgesResponse.data.badges.filter(badge => 
        !(badge.isOwned === true || (badge.status === 'minted' && badge.user_id === userId))
      );
      console.log(`   发现 ${invalidBadges.length} 个问题勋章:`);
      invalidBadges.forEach(badge => {
        console.log(`   - ${badge.badge_name || '未命名'} (状态: ${badge.status}, isOwned: ${badge.isOwned})`);
      });
    }
    
    // 5. 验证"可获得勋章"是否全部为未获得状态
    const availableVerification = availableBadgesResponse.data.badges.every(badge => 
      badge.isOwned === false && badge.status === 'available'
    );
    
    console.log('\n🔍 可获得勋章验证:');
    if (availableVerification) {
      console.log('✅ "可获得勋章"全部为未获得状态');
    } else {
      console.log('❌ "可获得勋章"中存在已获得的勋章');
      const invalidBadges = availableBadgesResponse.data.badges.filter(badge => 
        !(badge.isOwned === false && badge.status === 'available')
      );
      console.log(`   发现 ${invalidBadges.length} 个问题勋章:`);
      invalidBadges.forEach(badge => {
        console.log(`   - ${badge.badge_name || '未命名'} (状态: ${badge.status}, isOwned: ${badge.isOwned})`);
      });
    }
    
    // 6. 勋章ID唯一性验证
    const allBadgeIds = allBadgesResponse.data.badges.map(badge => badge.id);
    const uniqueIds = new Set(allBadgeIds);
    
    console.log('\n🔍 勋章ID唯一性验证:');
    if (allBadgeIds.length === uniqueIds.size) {
      console.log('✅ 所有勋章ID唯一');
    } else {
      console.log('❌ 存在重复的勋章ID');
      console.log(`   总勋章数: ${allBadgeIds.length}, 唯一ID数: ${uniqueIds.size}`);
      
      // 查找重复ID
      const idCounts = {};
      allBadgeIds.forEach(id => {
        idCounts[id] = (idCounts[id] || 0) + 1;
      });
      
      const duplicateIds = Object.entries(idCounts)
        .filter(([id, count]) => count > 1)
        .map(([id]) => id);
      
      console.log(`   重复ID: ${duplicateIds.join(', ')}`);
    }
    
    // 7. 总结
    console.log('\n📝 验证总结:');
    if (ownedVerification && availableVerification && (ownedCount + availableCount === totalCount)) {
      console.log('✅ 勋章筛选功能修复成功!');
      console.log('   - "我的勋章"仅显示已获得的勋章');
      console.log('   - "可获得勋章"仅显示未获得的勋章');
      console.log('   - 勋章总数一致性验证通过');
    } else {
      console.log('❌ 勋章筛选功能存在问题，需要进一步修复:');
      if (!ownedVerification) console.log('   - "我的勋章"包含未获得勋章');
      if (!availableVerification) console.log('   - "可获得勋章"包含已获得勋章');
      if (ownedCount + availableCount !== totalCount) console.log('   - 勋章总数不一致');
    }
    
  } catch (error) {
    console.error('❌ 验证过程出错:', error.message);
    if (error.response) {
      console.error('详细错误:', error.response.data);
    }
  }
})(); 